package com.zhiyume.oss;

import com.zhiyume.api.controller.AnyDetailController;
import com.zhiyume.service.util.DateUtil;
import com.zhiyume.util.ImageUtils;
import com.zhiyume.util.OSSClientUtil;
import com.zhiyume.util.TypeConstants;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.aspectj.weaver.tools.cache.SimpleCacheFactory.path;

/**
 * FroalaEditor测试
 */
@Controller
@RequestMapping("/oss")
public class OssUpload {

    private static final Logger logger = LoggerFactory.getLogger(AnyDetailController.class);

    @GetMapping(value="/ossImgUpload")
    public String ossUpload(){
        return "ossImgUpload";
    }


    /**
     * 上传至阿里云OSS
     * @param file
     * @param request
     * @throws FileNotFoundException
     */
    @PostMapping(value="/ossImgUpload")
    @ResponseBody
    public static Map ossUpload(@RequestParam(defaultValue="") String filedir,
                                @RequestParam(value="file")MultipartFile file,
                                @RequestParam(value="water",defaultValue = "0")String water,
                                HttpServletRequest request) throws FileNotFoundException {

        // 获取文件名
        String fileName = file.getOriginalFilename();
        logger.info("上传的文件名为：" + fileName);
        // 获取文件的后缀名

        String uploadFlag = "1"; // 0-上传成功 1-上传失败
        String uploadMsg = "上传成功"; // 上传返回提示

        String uploadUrl = "";

        if (!file.isEmpty()) {
            try {

                String rootPath = request.getSession().getServletContext().getRealPath("/");
                logger.info("OssUpload:服务器根路径【"+rootPath+"】");
                String filePath = rootPath+ "upload/";
                File dir = new File(filePath);
                if(! dir.exists()) {
                    dir.mkdir();
                }

                String path = filePath + file.getOriginalFilename();

                String md5Str = "";
                OSSClientUtil ossClientUtil = new OSSClientUtil(filedir);

                if(TypeConstants.COMMON_VALID.equals(water)){

                    md5Str = ossClientUtil.uploadImg2Oss(file);

                }else if(TypeConstants.COMMON_INVALID.equals(water)){

                    File tempFile = null;
                    //save to the /upload path
                    try {
                        tempFile = new File(path);
                        FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);
                    }catch (Exception E){
                        logger.error(E.getMessage());
                    }

                    //水印位置，水印位置，水印位置
                    String waterImg = rootPath+ "img/watermark/watermark.png";

                    ImageUtils.pressImage(tempFile,waterImg,5000,5000,0.8f);

                    try {
                        md5Str = ossClientUtil.uploadImg2Oss(file,tempFile);
                        //去掉图片缓存文件减少硬盘存储空间
                        if(tempFile!=null)tempFile.deleteOnExit();
                    }catch (Exception m){
                        logger.error(m.getMessage());
                    }

                }

                uploadUrl = ossClientUtil.getUrl("");

                logger.info(">>>>>>>>>>上传文件至阿里云返回串<<<<<<<<<"+md5Str);

                logger.info("------图片上传至阿里云的访问地址为---------" + uploadUrl);

            } catch (FileNotFoundException e) {
                uploadMsg = "上传失败,文件未找到";
                e.printStackTrace();

            } catch (IOException e) {
                uploadMsg = "上传失败,文件读取出错";
                e.printStackTrace();

            } catch (Exception e) {
                uploadMsg = "上传失败";
                e.printStackTrace();
            }

        } else {

            uploadFlag = "1";
            uploadMsg = "上传失败,图片不能为空";
        }

        Map<String,Object> data = new HashMap<String, Object>();
//        data.put("errno",uploadFlag);
//        data.put("data",picInfo);
        data.put("link",uploadUrl);

        return data;
    }

    /**
     * 图片删除
     * @param imgName
     */
    @RequestMapping("delPic")
    @ResponseBody
    public static Map delPic(@RequestParam String imgName){
        String result = "success";
        try {
            OSSClientUtil ossClientUtil = new OSSClientUtil();
            ossClientUtil.deleteFile(imgName);
        }catch (Exception e){
            result = "fail";
            e.printStackTrace();
        }

        Map map = new HashMap();
        map.put("result",result);
        return map;
    }

    /**
     * 删除指定目录下的指定图片
     * @param filedir
     * @param imgName
     * @return
     */
    @RequestMapping("delPicByDir")
    @ResponseBody
    public static Map delPic(@RequestParam String filedir,
                             @RequestParam String imgName){
        String result = "success";
        try {
            OSSClientUtil ossClientUtil = new OSSClientUtil(filedir);
            ossClientUtil.deleteFile(filedir,imgName);
        }catch (Exception e){
            result = "fail";
            e.printStackTrace();
        }

        Map map = new HashMap();
        map.put("result",result);
        return map;
    }

    /**
     * 根据图片名字和阿里云裁剪样式进行图片处理
     * @return
     */
    public static String getImgStyleUrl(String style,String imgName){
        OSSClientUtil ossClientUtil = new OSSClientUtil();
        String url = ossClientUtil.getImgSytleUrl(style,imgName);
        return url;
    }


    public static void main(String[] args) throws FileNotFoundException {
//        URL url = ResourceUtils.getURL("classpath:static/uploadImg/");
//        System.out.println(url.getPath());
//        System.out.println("123");
        OssUpload ossUpload = new OssUpload();
        String img = "data/20171017133709_psb.jpg";
        String style = "style/drama_width_height_rule";
        System.out.println("-----------阿里云图片处理后的地址为-----------"+ossUpload.getImgStyleUrl(style,img));
    }
}